package com.quyunshuo.module.home.activity.help

import android.app.Activity
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.quyunshuo.module.home.R
import kotlinx.coroutines.launch

@Composable
fun HelpPage() {
    Box {
        Column {
            HelpAppTitle(R.string.home_help_title)
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(100.dp)
            ) {
                Image(
                    painter = painterResource(R.drawable.setting_icon), contentDescription = null,
                    modifier = Modifier.fillMaxSize()
                )
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color(0x99000000))//我滴妈，，，，preview，预览不了R.drawable
                )
                Column(
                    modifier = Modifier
                        .align(Alignment.Center),  // 让Column在Box中居中
                    horizontalAlignment = Alignment.CenterHorizontally,//内容水平居中
                ) {
                    Text("正念冥想指南", color = Color.White, fontSize = 25.sp)
                    Text("一份给初学者的正念冥想指南", color = Color.White)
                }
            }
            //展示tablayout
            TabLayoutScreen()

        }
    }
}

@Composable
 fun HelpAppTitle(title:Int) {
    val context = LocalContext.current
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(60.dp)
            .background(colorResource(R.color.white))
    ) {
        // 图标（垂直居中在Box中）
        Image(
            painter = painterResource(R.drawable.home_return),
            contentDescription = null,
            modifier = Modifier
                .padding(start = 10.dp)
                .size(20.dp)
                .align(Alignment.CenterStart) // 左侧垂直居中
                .clickable {
                    (context as? Activity)?.finish()
                }
        )

        // 文本（在Box内水平和垂直居中）
        Text(
            text = stringResource(title),
            modifier = Modifier.align(Alignment.Center),
            textAlign = TextAlign.Center // 确保文字内容水平居中
        )
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TabLayoutScreen() {
    val tabs = listOf(
        "热门", "推荐", "体育"/*, "科技", "财经", "娱乐", "健康", "教育", "旅游", "美食"*/
    )
    val pagerState = rememberPagerState(pageCount = { tabs.size })
    //跳转到指定的位置
    val listState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()

    Column {
        // 1. Tab标签区域
        ScrollableTabRow(
            selectedTabIndex = pagerState.currentPage,
            contentColor = Color.Black,
            containerColor = Color(0xFFF5F5F5),
            indicator = {},
            divider = {},
            edgePadding = 0.dp,
            modifier = Modifier.height(50.dp)
        ) {
            tabs.forEachIndexed { index, title ->
                Text(
                    text = title,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .padding(end = 20.dp)
                        .background(
                            colorResource(R.color.base_colorPrimary),
                            shape = RoundedCornerShape(20.dp)
                        ).clickable {
                            coroutineScope.launch {
                                // 滚动到第5个（索引为4，因为索引从0开始）
                                listState.animateScrollToItem(index = index)
                                // 或者使用平滑滚动：scrollToItem也可以，但没有动画
                                // listState.scrollToItem(4)
                            }
                        }
                )
            }
        }

        // 2. 页面内容区域
        HorizontalPager(
            state = pagerState,
            modifier = Modifier.fillMaxSize()
        ) { page ->
            TabContentPage(tabIndex = page, title = tabs[page],listState)
        }
    }
}

@Composable
fun TabContentPage(tabIndex: Int, title: String, listState: LazyListState) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF5F5F5)),
        contentAlignment = Alignment.Center
    ) {
        LazyColumn(state = listState,modifier = Modifier.fillMaxSize()) {
            items(meditationGuides) { guide ->
                GuideSection(guide = guide)
            }
        }
    }
}

@Composable
fun GuideSection(guide: MeditationGuide) {
    var expanded by remember { mutableStateOf(false) }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(12.dp),
    ) {
        Column {
            // 一级标题部分
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { expanded = !expanded }
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = guide.title,
                    fontSize = 18.sp,
                    style = MaterialTheme.typography.titleLarge,
                    modifier = Modifier.weight(1f)
                )
            }
            Column(
                modifier = Modifier
                    .padding(horizontal = 16.dp)
                    .background(colorResource(R.color.white), RoundedCornerShape(20.dp))
                    .padding(5.dp),
            ) {
                guide.subTopics.forEachIndexed { index, subTopic ->
                    SubTopicItem(subTopic = subTopic)
                    // 只在非最后一个元素后添加分割线
                    if (index < guide.subTopics.lastIndex) {
                        Spacer(Modifier.height(10.dp))
                        Box(
                            Modifier
                                .fillMaxWidth()
                                .height(1.dp)
                                .alpha(0.1f)
                                .padding(horizontal = 10.dp)
                                .background(colorResource(R.color.color_2E2E2E))
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun SubTopicItem(subTopic: SubTopic) {
    var expanded by remember { mutableStateOf(false) }
    val rotationAngle by animateFloatAsState(
        targetValue = if (expanded) 270f else 180f,
        animationSpec = tween(durationMillis = 200) // 设置动画时长
    )

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
            .clickable { expanded = !expanded }
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {

            Spacer(Modifier.width(8.dp))
            Text(
                text = subTopic.title,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Medium,
                fontSize = 16.sp,
                color = colorResource(R.color.color_2E2E2E),
                modifier = Modifier.weight(1f)
            )
            Spacer(Modifier.weight(1f))
            Image(
                painter = painterResource(R.drawable.home_return),
                contentDescription = null,
                modifier = Modifier
                    .size(15.dp)
                    .alpha(0.3f)
//                    .rotate(if(expanded)270f else 180f)
                    .rotate(rotationAngle)//旋转的时候增加动画。
            )
            Spacer(Modifier.width(10.dp))

        }

        if (expanded) {
            Text(
                text = subTopic.content,
                fontSize = 12.sp,
                modifier = Modifier.padding(start = 24.dp, top = 8.dp, end = 8.dp),
                style = MaterialTheme.typography.bodyLarge
            )
        }

    }
}

@Preview
@Composable
fun HelpPagePreview() {
    HelpPage()
}